﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OrganizedIN.UI.GroupContact
{
    public partial class Messages : System.Web.UI.Page
    {
        OIDataContext dc = new OIDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    ContactViewPanel.Visible = true;
                    ContactThreadPanel.Visible = false;
                    BindContactMessageRepeater();
                }
            }
            catch (Exception ex) { }
        }
        #region ContactMessages
        #region ControlEvents
        protected void btnSendmsg_Click(object sender, EventArgs e)
        {
            tblMessage msg = PostMessage(ddlContact.SelectedValue, txtUMessage.Text, 0);
            dc.tblMessages.InsertOnSubmit(msg);
            dc.SubmitChanges();
            BindContactThread(ddlContact.SelectedValue, 0);
            txtUMessage.Text = "";
            ddlContact.SelectedIndex = 0;
        }

        protected void lnkBack_Click(object sender, EventArgs e)
        {
            ContactViewPanel.Visible = true;
            ContactThreadPanel.Visible = false;
            BindContactMessageRepeater();
        }
        #endregion

        #region DataBindingMethods
        private void BindContactMessageRepeater()
        {
            var data = (from d in dc.tblMessages
                        where d.ToUname == Session["UserID"].ToString() || d.FromUname == Session["UserID"].ToString()
                        select new
                        {
                            Name = d.FromUname == Session["UserID"].ToString() ? d.UserInformation1.FirstName + " " + d.UserInformation1.LastName : d.UserInformation.FirstName + " " + d.UserInformation.LastName,
                            username = d.FromUname == Session["UserID"].ToString() ? d.ToUname : d.FromUname,
                            ProfilePicture = d.FromUname == Session["UserID"].ToString() ? ((d.UserInformation1.ProfilePicture == null || d.UserInformation1.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.UserInformation1.ProfilePicture) : ((d.UserInformation.ProfilePicture == null || d.UserInformation.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.UserInformation.ProfilePicture),
                            UnreadCount = "(" + (from da in dc.tblMessages where da.ToUname == Session["UserID"].ToString() && da.IsRead == false select d.MessageID).Count().ToString() + ")"
                        }).Distinct();
            rptrUsers.DataSource = data;
            rptrUsers.DataBind();
        }

        private void BindContactThread(string RefName, int GroupID)
        {
            if (RefName != null)
            {
                var msgs = (from d in dc.tblMessages
                            where (d.FromUname == Session["UserID"].ToString() && d.ToUname == RefName) || (d.ToUname == Session["UserID"].ToString() && d.FromUname == RefName)
                            orderby d.PostDate ascending
                            select new { d.Message, Name = d.UserInformation.FirstName + " " + d.UserInformation.LastName, username = d.FromUname, d.PostDate, d.MessageID, ProfilePicture = (d.UserInformation.ProfilePicture == null || d.UserInformation.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.UserInformation.ProfilePicture, IsOwn = d.UserInformation.username == Session["UserID"] ? true : false, d.IsRead });
                rptrContactThread.DataSource = msgs;
                rptrContactThread.DataBind();
            }
            else
            {
                var msgs = (from d in dc.tblMessages
                            where (d.Group_ID == GroupID)
                            orderby d.PostDate ascending
                            select new { d.Message, Name = d.UserInformation.FirstName + " " + d.UserInformation.LastName, username = d.FromUname, d.PostDate, d.MessageID, ProfilePicture = (d.UserInformation.ProfilePicture == null || d.UserInformation.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.UserInformation.ProfilePicture, IsOwner = d.UserInformation.username == d.Group_Master.User_Organizer_Mapping.username ? true : false });
                rptrGroupThread.DataSource = msgs;
                rptrGroupThread.DataBind();
            }
        }
        #endregion

        #region RepeaterMethods
        protected void rptrUsers_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "select")
            {
                ViewState["CurrContact"] = e.CommandArgument.ToString();
                BindContactThread(e.CommandArgument.ToString(), 0);
                ContactViewPanel.Visible = false;
                ContactThreadPanel.Visible = true;
                MarkMessagesAsRead(e.CommandArgument.ToString(), 0);
                lnkBack.Focus();
            }
        }

        protected void rptrContactThread_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                tblMessage msg = PostMessage(e.CommandArgument.ToString(), ((TextBox)e.Item.FindControl("txtUMessage")).Text, 0);
                dc.tblMessages.InsertOnSubmit(msg);
                dc.SubmitChanges();
                BindContactThread(e.CommandArgument.ToString(), 0);
                lnkBack.Focus();
            }
            else
            {
                if (e.CommandName == "delete")
                {
                    var data = (from d in dc.tblMessages
                                where d.MessageID == Convert.ToInt64(e.CommandArgument)
                                select d).SingleOrDefault();
                    dc.tblMessages.DeleteOnSubmit(data);
                    dc.SubmitChanges();
                    BindContactThread(data.FromUname == Session["UserID"].ToString() ? data.ToUname : data.FromUname, 0);
                }
            }
        }

        protected void rptrContactThread_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                ((Button)e.Item.FindControl("btnSendmsg")).CommandArgument = ViewState["CurrContact"].ToString();
            }
        }
        #endregion

        #region FunctionalMethods
        public string GetBGColor(object IsRead, object IsOwn)
        {
            string style = "padding-top: 5px;";
            if (IsRead != null)
            {
                if ((bool)IsRead == false && (bool)IsOwn == false)
                {
                    style += "background-color:#F2F2F2";
                }
            }
            return style;
        }

        private void MarkMessagesAsRead(string FromUName, int GroupID)
        {
            List<tblMessage> messages = new List<tblMessage>();
            if (GroupID == 0)
            {
                messages = (from d in dc.tblMessages
                            where d.ToUname == Session["UserID"].ToString() && d.FromUname == FromUName
                            select d).ToList();
            }
            else
            {
                messages = (from d in dc.tblMessages
                            where d.ToUname == Session["UserID"].ToString() && d.Group_ID == GroupID
                            select d).ToList();
            }
            messages.ForEach(ms => ms.IsRead = true);
            dc.SubmitChanges();
        }
        #endregion
        #endregion

        #region GroupMessages

        #region ControlEvents

        protected void btnSendGroupMessage_Click(object sender, EventArgs e)
        {
            //List<tblMessage> msgs = new List<tblMessage>();
            //var data = (from d in dc.Group_Contact_Mappins
            //                where d.Group_ID == Convert.ToInt32(ddlGroup.SelectedValue)
            //                select d.username);
            //foreach (string s in data)
            //{ 
            //    msgs.Add(PostMessage(s,txtGMessage.Text,Convert.ToInt32(ddlGroup.SelectedValue));
            //}
            //dc.tblMessages.InsertAllOnSubmit(msgs);
            //dc.SubmitChanges();
            tblMessage msg = PostMessage(null, txtGMessage.Text, Convert.ToInt32(ddlGroup.SelectedValue));
            dc.tblMessages.InsertOnSubmit(msg);
            dc.SubmitChanges();
            BindContactThread(null, Convert.ToInt32(ddlGroup.SelectedValue));
            txtGMessage.Text = "";
            ddlGroup.SelectedIndex = 0;
        }

        protected void lnkGBack_Click(object sender, EventArgs e)
        {
            GroupViewPanel.Visible = true;
            GroupThreadPanel.Visible = false;
            rptrGroups.DataBind();
        }
        #endregion

        #region RepeaterMethods
        protected void rptrGroups_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "select")
            {
                ViewState["CurrGroup"] = e.CommandArgument.ToString();
                BindContactThread(null, Convert.ToInt32(e.CommandArgument.ToString()));
                GroupViewPanel.Visible = false;
                GroupThreadPanel.Visible = true;
                lnkGBack.Focus();
            }
        }

        protected void rptrGroupThread_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                tblMessage msg = PostMessage(null, ((TextBox)e.Item.FindControl("txtGMessage")).Text, Convert.ToInt32(e.CommandArgument.ToString()));
                dc.tblMessages.InsertOnSubmit(msg);
                dc.SubmitChanges();
                BindContactThread(null, Convert.ToInt32(e.CommandArgument.ToString()));
                lnkGBack.Focus();
            }
            else
            {
                if (e.CommandName == "delete")
                {
                    var data = (from d in dc.tblMessages
                                where d.MessageID == Convert.ToInt64(e.CommandArgument)
                                select d).SingleOrDefault();
                    dc.tblMessages.DeleteOnSubmit(data);
                    dc.SubmitChanges();
                    BindContactThread(null, data.Group_ID.Value);
                }
            }
        }

        protected void rptrGroupThread_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                ((Button)e.Item.FindControl("btnGroupSendmsg")).CommandArgument = ViewState["CurrGroup"].ToString();
            }
        }
        #endregion

        #endregion

        private tblMessage PostMessage(string ToUname, string Message, int GroupID)
        {
            tblMessage msg = new tblMessage();
            msg.FromUname = Session["UserID"].ToString();
            if (ToUname != null)
            {
                msg.ToUname = ToUname;
            }
            msg.Message = Message;
            msg.PostDate = DateTime.Now;
            if (GroupID != 0)
            {
                msg.Group_ID = GroupID;
            }
            msg.IsRead = false;
            return msg;
        }
    }
}
